package com.kld.shop.controller.product;

import com.alibaba.fastjson.JSON;
import com.kld.common.framework.dto.ProductNode;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.dto.TreeNode;
import com.kld.common.util.BuildTreeUtil;
import com.kld.common.util.CreateFileName;
import com.kld.common.util.FileOperateUtil;
import com.kld.product.api.IProBrandService;
import com.kld.product.api.IProCategoryService;
import com.kld.product.api.IProProductService;
import com.kld.product.api.IProPropService;
import com.kld.product.dto.CategoryDto;
import com.kld.product.po.ProBrand;
import com.kld.product.po.ProCategory;
import com.kld.product.po.ProProp;
import com.kld.shop.allocation.Constant;
import com.kld.shop.controller.base.BaseController;
import com.kld.shop.utils.FastDfsUtil;
import com.kld.sys.po.SysDict;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import utils.CategoryUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by anpushang on 2016/3/28.
 */
@Controller
@RequestMapping("/admin/cate")
public class ProCategoryController extends BaseController{

    @Autowired
    private IProCategoryService proCategoryService;
    @Autowired
    private IProBrandService proBrandService;
    @Autowired
    private IProPropService proPropService;
    @Autowired
    private IProProductService proProductService;

    /***
     * 进入列表页面
     * @return
     */
    @RequestMapping(value = "/toList")
    public String toList(){
        return "/admin/category/category_list";
    }

    /***
     * 分类列表集合查询
     * @param proCategory
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/list")
    public String list(ProCategory proCategory){
        String str = null;
        try{
            proCategory.setIsDel(Constant.ENABLE);
            List<ProCategory> proCategoryList = proCategoryService.findProCategoryList(proCategory);
            List<CategoryDto> proCategories = CategoryUtils.buildCategoryTree(proCategoryList, 0);
            JSONArray jsonArray = JSONArray.fromObject(proCategories);
            if (jsonArray.size() > 0) {
                str = JSON.toJSONString(jsonArray);
            }
        }catch (Exception e){
            logger.error("类目查询"+e.getMessage(),e);
            e.printStackTrace();
        }
        return str;
    }

    /***
     * 查询当前分类下的子集分类
     * @param categoryId
     * @throws Exception
     */
    @ResponseBody()
    @RequestMapping(value = "/getSub/{categoryId}/{lev}")
    public ResultMsg getSub(@PathVariable int categoryId,@PathVariable int lev){
        ResultMsg resultMsg = new ResultMsg();
        try{
            if (lev == 3){
                //查看三级分类是否被商品使用
                int count = proProductService.findCategoryIsProductById(categoryId);
                resultMsg = count > 0 ? successMsg(resultMsg,"该分类已被使用,不允许删除") : errorMsg(resultMsg,Constant.UPDATE_ERROR);
            }else{
                int count = proCategoryService.getCateChildById(categoryId);
                resultMsg = count > 0 ? successMsg(resultMsg,"该分类下有子分类,不允许删除") : errorMsg(resultMsg,Constant.UPDATE_ERROR);
            }
        }catch (Exception e){
            logger.error("查询子分类"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }

    /**
     * 分类新增
     * @param proCategory 分类对象
     * @param brandArray 品牌集合
     * @param propertyArray 属性集合
     * @param specArray 规格结合D
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/saveCategory", method = RequestMethod.POST)
    public ResultMsg saveCategory(ProCategory proCategory,
                                  Integer[] brandArray, Integer[] propertyArray,Integer[] specArray){
        ResultMsg resultMsg = new ResultMsg();
        try {
            int resultCount = 0;
            proCategory.setIsDel(Constant.ENABLE);
//            proCategory.setState(Constant.ENABLE);
            if (proCategory.getLev() == 3){// 判断上级分类的级别，如果是2，那么此动作是添加三级分类
                List<Integer> propertys = new ArrayList<Integer>();
                if(null != propertyArray && propertyArray.length > 0){
                    propertys = Arrays.asList(propertyArray);
                }
                List<Integer> brands = new ArrayList<Integer>();
                if(null != brandArray && brandArray.length > 0 ){
                    brands = Arrays.asList(brandArray);
                }
                List<Integer> specs = new ArrayList<Integer>();
                if(null != specArray && specArray.length > 0){
                    specs = Arrays.asList(specArray);
                }
                proCategory.setPropertyList(propertys);
                proCategory.setSpecsList(specs);
                proCategory.setBrandList(brands);
                resultCount = proCategoryService.insertChildCategory(proCategory);
            }else {
                resultCount = proCategoryService.insert(proCategory);
            }
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.INSERT_SUCCESS) : errorMsg(resultMsg,Constant.INSERT_ERROR);
        }catch (Exception e){
            logger.error("查询子分类"+e.getMessage(),e);
            errorMsg(resultMsg,Constant.INSERT_ERROR);
            e.printStackTrace();
        }
        return resultMsg;
    }


    /**
     * 分类修改
     * @param proCategory 分类对象
     * @param brandArray 品牌集合
     * @param propertyArray 属性集合
     * @param specArray 规格结合D
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/upCategory", method = RequestMethod.POST)
    public ResultMsg upCategory(ProCategory proCategory,
                                  Integer[] brandArray, Integer[] propertyArray,Integer[] specArray){
        ResultMsg resultMsg = new ResultMsg();
        try {
            int resultCount = 0;
            proCategory.setIsDel(Constant.ENABLE);
            if (proCategory.getLev() == 3){// 判断上级分类的级别，如果是2，那么此动作是添加三级分类
                List<Integer> propertys = new ArrayList<Integer>();
                if(null != propertyArray && propertyArray.length > 0){
                    propertys = Arrays.asList(propertyArray);
                }
                List<Integer> brands = new ArrayList<Integer>();
                if(null != brandArray && brandArray.length > 0 ){
                    brands = Arrays.asList(brandArray);
                }
                List<Integer> specs = new ArrayList<Integer>();
                if(null != specArray && specArray.length > 0){
                    specs = Arrays.asList(specArray);
                }
                proCategory.setPropertyList(propertys);
                proCategory.setSpecsList(specs);
                proCategory.setBrandList(brands);
                resultCount = proCategoryService.updateChildCategory(proCategory);
            }else {
                resultCount = proCategoryService.updateByPrimaryKey(proCategory);
            }
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.INSERT_SUCCESS) : errorMsg(resultMsg,Constant.INSERT_ERROR);
        }catch (Exception e){
            logger.error("查询子分类"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }

    /***
     * 上下架分类操作
     * @param proCategory
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/changePutAway")
    public ResultMsg changePutAway(ProCategory proCategory){
        ResultMsg resultMsg = new ResultMsg();
        try{
            int resultCount = proCategoryService.updateChangePutAway(proCategory);
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.UPDATE_SUCCESS) : errorMsg(resultMsg,Constant.UPDATE_ERROR);
        }catch (Exception e){
            logger.error("上下架分类操作"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }


    /***
     * 删除分类操作
     * @param proCategory
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/deleteCate")
    public ResultMsg deleteCate(ProCategory proCategory){
        ResultMsg resultMsg = new ResultMsg();
        try{
            proCategory.setIsDel(Constant.DISABLE);
            int resultCount = proCategoryService.updateByPrimaryKey(proCategory);
            resultMsg = resultCount > 0 ? successMsg(resultMsg,Constant.DELETE_SUCCESS) : errorMsg(resultMsg,Constant.DELETE_ERROR);
        }catch (Exception e){
            logger.error("删除分类操作"+e.getMessage(),e);
            e.printStackTrace();
        }
        return resultMsg;
    }


    @ResponseBody()
    @RequestMapping(value = "/getCategory")
    public String getCategory(ProCategory proCategory){
        String jsonStr = "";
        try{
            List<TreeNode> nodes = new ArrayList<TreeNode>();
            proCategory.setLev(3);
            proCategory.setIsDel(Constant.ENABLE);
            List<ProCategory> proCategoryList = proCategoryService.findCategoryListByLev(proCategory);//查询一二级级分类
            for (ProCategory cateGory : proCategoryList) {
                TreeNode treeNode = new TreeNode();
                treeNode.setId(String.valueOf(cateGory.getId()));
                treeNode.setPid(String.valueOf(cateGory.getpId()));
                treeNode.setText(cateGory.getCateName());
                treeNode.setLevel(cateGory.getLev());
                treeNode.setHaschild(cateGory.getHasChild());
                nodes.add(treeNode);
            }
            List<TreeNode> treeNodes = BuildTreeUtil.buildtree(nodes, "0","category");
            JSONArray jsonArray = JSONArray.fromObject(treeNodes);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", 0);
            jsonObject.put("text", "商品分类");
            jsonObject.put("level", 0);
            jsonArray.add(jsonObject);
            jsonStr = String.format("%s", JSON.toJSONString(jsonArray));
        }catch (Exception e){
            logger.error("获取一二级分类操作"+e.getMessage(),e);
            e.printStackTrace();
        }
        return jsonStr;
    }


    /**
     * 到添加分类界面
     * @return
     */
    @RequestMapping(value = "/toAddCatePage")
    public ModelAndView toAddCatePage(ProCategory proCategory){
        ModelAndView modelAndView = new ModelAndView();
        try{
            ProBrand proBrand = new ProBrand();
            proBrand.setIsDel(Constant.ENABLE);
            List<ProBrand> proBrandList = proBrandService.findProBrandList(proBrand);//品牌集合
            ProProp proProp = new ProProp();
            proProp.setState(Constant.ENABLE);
            proProp.setIsSpec(1);
            List<ProProp> specsList = proPropService.findProProductList(proProp);//加载规格
            proProp.setIsSpec(0);
            List<ProProp> proPropList = proPropService.findProProductList(proProp);//加载属性
            modelAndView.addObject("proBrandList", proBrandList);
            modelAndView.addObject("specsList", specsList);
            modelAndView.addObject("proPropList", proPropList);
            modelAndView.setViewName("/admin/category/category_add");
        }catch (Exception e){
            logger.error("到添加分类界面"+e.getMessage(),e);
            e.printStackTrace();
        }
        return modelAndView;
    }

    /***
     * 到编辑界面
     * @param proCategory
     * @return
     */
    @RequestMapping(value = "/toUpdateCatePage")
    public ModelAndView toUpdateCatePage(ProCategory proCategory){
        ModelAndView modelAndView = new ModelAndView();
        try{
            //查询已选品牌
            List<ProBrand> proBrands = proBrandService.findProBrandByCateId(proCategory.getId());
            //查询已选属性
            List<ProProp> proProps = proPropService.findPropByCateId(proCategory.getId(),0);
            //查询已选规格
            List<ProProp> propSpecs = proPropService.findPropByCateId(proCategory.getId(),1);

            ProCategory category = proCategoryService.selectByPrimaryKey(proCategory.getId());

            ProBrand proBrand = new ProBrand();
            proBrand.setIsDel(Constant.ENABLE);
            List<ProBrand> proBrandList = proBrandService.findProBrandList(proBrand);//品牌集合
            ProProp proProp = new ProProp();
            proProp.setState(Constant.ENABLE);
            proProp.setIsSpec(1);
            List<ProProp> specsList = proPropService.findProProductList(proProp);//加载规格
            proProp.setIsSpec(0);
            List<ProProp> proPropList = proPropService.findProProductList(proProp);//加载属性

            modelAndView.addObject("proBrandList", proBrandList);
            modelAndView.addObject("specsList", specsList);
            modelAndView.addObject("proPropList", proPropList);
            modelAndView.addObject("category", category);

            modelAndView.addObject("proBrands", proBrands);
            modelAndView.addObject("proProps", proProps);
            modelAndView.addObject("propSpecs", propSpecs);
            modelAndView.setViewName("/admin/category/category_edit");
        }catch (Exception e){
            logger.error("到编辑分类界面"+e.getMessage(),e);
            e.printStackTrace();
        }
        return modelAndView;
    }

    /***
     * 查看详情
     * @param proCategory
     * @return
     */
    @RequestMapping(value = "/lookDetail")
    public ModelAndView lookDetail(ProCategory proCategory){
        ModelAndView modelAndView = toUpdateCatePage(proCategory);
        modelAndView.setViewName("/admin/category/category_detail");
        return modelAndView;
    }



    @ResponseBody
    @RequestMapping("/uploadPic")
    public ResultMsg uploadPic(MultipartFile file) {
        String msg = "";
        ResultMsg result = new ResultMsg();
        boolean tag = false;
        String path = request.getSession().getServletContext().getRealPath("upload/category");
//        System.out.println("图片地址："+path);
        //为上传的文件生成一个唯一名字
        String fileName = "";
        String fileUrl = "";
        if ("".equals(file.getOriginalFilename())) {
            fileName = "default.png";
            fileUrl = "/upload/category/" + fileName;
        } else {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            if (!FileOperateUtil.IsAllowImgExt(ext)) {
                result.setResult(false);
                result.setMsg("不允许上传" + ext + "类型的文件.");
                return result;
            }
            fileName = CreateFileName.getFileName() + ext;
            File targetFile = new File(path, fileName);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                //保存文件
                file.transferTo(targetFile);
                /*String fileUrl=request.getContextPath()+"/upload/"+fileName;*/
                fileUrl = "/upload/category/" + fileName;
                tag = true;
                msg = fileUrl;
//                System.out.println("文件路径：" + fileUrl);
//                System.out.println("文件上传成功");
            } catch (IllegalStateException e) {
                logger.info("上传图片失败:" + e.getMessage(), e);
            } catch (IOException e) {
                logger.info("上传图片失败:"+e.getMessage(),e);
            }
        }

        result.setResult(tag);
        result.setMsg(msg);
        return result;
    }

    /***
     * 根据父级ID去查询子集分类信息
     * @param pId 父级ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getCateByPid")
    public String getCateByPid(Integer pId){
        String jsonStr = "";
        try{
            List<ProCategory> proCategoryList = proCategoryService.selectCateByPid(pId);
            List<ProductNode> productNodeList = new ArrayList<ProductNode>();
            for (ProCategory proCategory : proCategoryList) {
                ProductNode productNode = new ProductNode();
                productNode.setId(String.valueOf(proCategory.getId()));
                productNode.setPid(String.valueOf(proCategory.getpId()));
                productNode.setText(proCategory.getCateName());
                productNodeList.add(productNode);
            }
            JSONArray jsonArray = JSONArray.fromObject(productNodeList);
            jsonStr = String.format("%s", JSON.toJSONString(jsonArray));
        }catch (Exception e){
            logger.error("根据父级ID去查询子集分类信息"+e.getMessage(),e);
            e.printStackTrace();
        }
        return jsonStr;
    }

}
